using System.Threading;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.EventBroker;
using Microsoft.Practices.ObjectBuilder;
using OrdersManager.Infrastructure.Interface;
using OrdersManager.Module.BusinessEntities;
using OrdersManager.Module.Constants;
using System.Globalization;

namespace OrdersManager.Module.Services
{
	public class OrderPollingService : IOrderPollingService
	{
		private const int DEFAULT_INTERVAL = 500;

		private int _interval;
		private IOrderService _orderService;
		private OrderStatus _orderStateMode;
		private Thread _thread;
		private WorkItem _workItem;

		[InjectionConstructor]
		public OrderPollingService([ServiceDependency] IOrderService orderService,
		                           [ServiceDependency] WorkItem workItem,
		                           [ComponentDependency("OrderStateMode")] OrderStatus orderStateMode)
		{
			_orderService = orderService;
			_orderStateMode = orderStateMode;
			_workItem = workItem;
		}

		public int Interval
		{
			get { return _interval; }
			set { _interval = value; }
		}

		public void Start()
		{
			Start(DEFAULT_INTERVAL);
		}

		public void Start(int interval)
		{
			_interval = interval;
			_thread = new Thread(new ThreadStart(GetOrders));
            _thread.Name = string.Format(CultureInfo.CurrentCulture, "[{0}.OrderPollingService]", _orderStateMode);
			_thread.Start();
		}

		public void Stop()
		{
			if (_thread != null)
			{
				_thread.Abort();
			}
		}

		private void GetOrders()
		{
			while (true)
			{
				if (_orderStateMode != OrderStatus.Initial)
				{
					//Get orders from service
					OrderCollection orders = _orderService.GetOrdersByState(_orderStateMode);

					//Fire a event topic and pass the orders as argument
					_workItem.EventTopics[EventTopicNames.OrdersLoaded].Fire(
						this,
						new EventArgs<OrderCollection>(orders),
						_workItem,
						PublicationScope.WorkItem);
					Thread.Sleep(_interval);
				}
			}
		}
	}
}